import axios, {
  type AxiosError,
  type AxiosRequestConfig,
  type InternalAxiosRequestConfig
} from 'axios'

interface AxiosRequestConfigEx extends AxiosRequestConfig {
  donNotShowLoading?: boolean
}

export type ResType<T = any> = {
  code: string
  data: T
  msg: string
}

export type PageDataType<T> = {
  list: T[]
  pageNum: number
  pageSize: number
  total: number
}

export type RolesType = {
  code: string
  createTime?: string
  id?: number
  name: string
  sort: number
  status: number
}

const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_PATH,
  timeout: 2000
})

// const BASE_URl_TEST = 'http://goapi.sanjitian.cn/api'
const BASE_URl_TEST = import.meta.env.VITE_BASE_PATH

// # 以前接口规范
// get: 获取数据，删除数据
// post ： 修改数据，修改状态，添加数据

// # rest接口规范 :使用接口的请求方式+请求的资源路径 做到接口请求的唯一性
// get:获取数据
// post:添加数据
// put :修改数据
// patch ：修改单个字段
// delete: 删除数据

// 角色分页列表
export const getRolesPage = async () => {
  try {
    const res = await fetch(BASE_URl_TEST + '/roles/page?pageNum=1&pageSize=50000', {
      method: 'GET'
    })
    return res.json()
  } catch (error) {
    console.log('error')
  }
}

export const postRoles = async () => {
  const myHeaders = new Headers()
  // 设置请求携带的数据格式是 JSON格式
  myHeaders.append('Content-Type', 'application/json')
  // 添加的 自定义的 header 信息（通常用户使用的秘钥会放到这里，后端接受之后用于判断用户是否登录）
  myHeaders.append(
    'Authorization',
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJSW5mbyI6eyJ1c2VySWQiOjIsInVzZXJuYW1lIjoiYWRtaW4iLCJuaWNrbmFtZSI6Iuezu-e7n-euoeeQhuWRmGFkbWluIiwiZGVwdElkIjoxLCJyb2xlcyI6IkFETUlOIn0sImlzcyI6ImR5czYyMzAiLCJleHAiOjE3Mjg5MDk5MTgsIm5iZiI6MTcyODg3MzkyOCwiaWF0IjoxNzI4ODczOTE4fQ.9xhdL57Qs38Mlm0K-TCwgrQjET1ZS2jUZhIOob0-pGk'
  )

  const newRole = {
    id: 5211314,
    name: '挽歌',
    code: '5211314',
    sort: 2,
    status: 1,
    dataScope: 3
  }

  // fetch 配置项
  const requestOptions = {
    // 请求方式 GET POST DELETE  PUT
    method: 'POST',
    // 设置 请求的 header 头信息
    headers: myHeaders,
    // 请求携带的数据
    body: JSON.stringify(newRole)
  }
  const res = await fetch('http://goapi.sanjitian.cn/api/roles', requestOptions)

  console.log(res)

  if (res.ok) {
    return res.json()
    // const resJson = await res.json()
    // console.log(resJson, 'resJson')
  }
}

// 通过角色的id 修改角色的数据
export const putRolesByRoleID = () => {
  const myHeaders = new Headers()
  myHeaders.append('Content-Type', 'application/json')

  const raw = JSON.stringify({
    name: '我爱你吗',
    code: '520',
    sort: 0,
    status: 1,
    dataScope: 0
  })

  const requestOptions = {
    method: 'PUT',
    headers: myHeaders,
    body: raw
  }

  fetch(BASE_URl_TEST + '/roles/1231235', requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log('error', error))
}

// 删除角色
export const deleteRolesByids = (id: string) => {
  const requestOptions = {
    method: 'DELETE'
  }

  fetch(BASE_URl_TEST + `/roles/${id}`, requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log('error', error))
}

// 修改status
export const patchRolesStatusByRoleID = () => {
  const requestOptions = {
    method: 'PATCH'
  }

  fetch('http://goapi.sanjitian.cn/api/roles/165484464/status?status=2', requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log('error', error))
}

// 服务请求
export const service = <T = any>(config: AxiosRequestConfigEx) => {
  return instance.request<ResType<T>>(config).then((response) => {
    return response.data
  })
  // .catch(error => console.error(error));
}

// http request 拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 使用 set 方法来设置 headers
    config.headers.set('Content-Type', 'application/json')
    return config
  },
  (error: AxiosError) => {
    // 请求报错
    Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    // 响应成功时做一些处理
    console.log('响应拦截器：', response)
    return response
  },
  (error) => {
    // 统一处理错误信息
    if (error.response.status === 401) {
      // 如果是 401 错误，可能是未授权，跳转到登录页面
      window.location.href = '/login'
    } else if (error.response.status === 500) {
      // 服务器错误
      console.error('服务器错误')
    }

    return Promise.reject(error)
  }
)

export const requestGetRolesPage = (params: any) => {
  return service<PageDataType<RolesType>>({
    method: 'get ',
    url: '/roles/page',
    params
  })
}
// const requestGetRolesPageHandler3 = async () => {
//   const res = await requestGetRolesPage({ pageNum: 1, pageSize: 40 })
//   console.log(res)
//   // roles.value = res.data.list
// }

/**
 * 添加角色
 * @param data
 * @returns
 */
export const addRole = (data: any) => {
  return service({
    method: 'post ',
    url: '/roles',
    data
  })
}

/**
 * 修改角色的数据
 * @param data
 * @returns
 */
export const editRole = (roleId: string, data: RolesType) => {
  service({
    method: 'put',
    url: `/roles/${roleId}`,
    data
  })
}

export const editRoleStaus = (roleId: string, status: number) => {
  return service({
    method: 'patch',
    url: `/roles/${roleId}/status`,
    params: { status }
  })
}

/**
 * 删除角色
 * @param ids
 */
export const delRole = (ids: string) => {
  instance
    .request({
      method: 'delete',
      url: `/roles/${ids}`
    })
    .then((response) => console.log('Deleted:', response.data))
    .catch((error) => console.error(error))
}

export const getRolePageHandlerAxios = () => {
  const config = {
    method: 'get',
    url: 'http://goapi.sanjitian.cn/api/roles/options',
    headers: {
      'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
      Authorization: ''
    }
  }

  return axios(config)
}

export const kuangbaotianjia = async () => {
  const requests = []

  for (let a = 50000; a <= 100000; a++) {
    const newRole = {
      id: a,
      name: `崔梦娇${a}`,
      code: `${a}`,
      sort: 2,
      status: 1,
      dataScope: 3
    }

    const requestOptions = {
      method: 'post',
      url: 'http://goapi.sanjitian.cn/api/roles', // 确保URL是正确的
      headers: {
        'Content-Type': 'application/json',
        Authorization:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJSW5mbyI6eyJ1c2VySWQiOjIsInVzZXJuYW1lIjoiYWRtaW4iLCJuaWNrbmFtZSI6Iuezu-e7n-euoeeQhuWRmGFkbWluIiwiZGVwdElkIjoxLCJyb2xlcyI6IkFETUlOIn0sImlzcyI6ImR5czYyMzAiLCJleHAiOjE3Mjg5MDk5MTgsIm5iZiI6MTcyODg3MzkyOCwiaWF0IjoxNzI4ODczOTE4fQ.9xhdL57Qs38Mlm0K-TCwgrQjET1ZS2jUZhIOob0-pGk'
      },
      data: newRole
    } // 发送请求并处理响应

    axios(requestOptions)
      .then((response) => {
        console.log(response) // 打印每次请求的响应
        // 可以在这里处理每次添加后的逻辑，例如检查响应状态
        if (response.status === 200) {
          console.log('Data added successfully:', response.data)
        } else {
          console.error('Failed to add data:', response.status)
        }
      })
      .catch((error) => {
        console.error('Error in postRoles:', error)
      }) // 将请求添加到数组中，以便后续可能的错误处理或日志记录

    requests.push(requestOptions)
  } // 如果需要处理所有请求后的逻辑，可以在这里添加

  console.log('All requests have been sent.')
}
